package com.henchman.samples;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNProperty;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

/**
 * 
 * @author Raghunathan Semburakkiannan
 *
 */

public class DisplayFile {

	public static void main(String[] args) {
		DAVRepositoryFactory.setup();

		String url = "http://svn.svnkit.com/repos/svnkit/trunk";
		String name = "anonymous";
		String password = "anonymous";
		String filePath = "LICENSE.txt";

		SVNRepository repository = null;
		try {
			repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(url));
			ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(name, password);
			repository.setAuthenticationManager(authManager);

			SVNNodeKind nodeKind = repository.checkPath(filePath, -1);

			if (nodeKind == SVNNodeKind.NONE) {
				System.err.println("There is no entry at '" + url + "'.");
				System.exit(1);
			} else if (nodeKind == SVNNodeKind.DIR) {
				System.err.println("The entry at '" + url
						+ "' is a directory while a file was expected.");
				System.exit(1);
			}
			Map fileProperties = new HashMap();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			//repository.getFile(filePath, -1, fileProperties, baos);

			String mimeType = (String) fileProperties.get(SVNProperty.MIME_TYPE);
			boolean isTextType = SVNProperty.isTextMimeType(mimeType);

			Iterator iterator = fileProperties.keySet().iterator();
			while (iterator.hasNext()) {
				String propertyName = (String) iterator.next();
				String propertyValue = (String) fileProperties.get(propertyName);
				System.out.println("File property: " + propertyName + "="+ propertyValue);
			}

			if (isTextType) {
				System.out.println("File contents:");
				System.out.println();
				try {
					baos.writeTo(System.out);
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
			} else {
				System.out.println("Not a text file.");
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}
}